import {observable, action, toJS} from 'mobx';
import CommonStore from '../CommonStore';
import * as PLANMODULAPI from '../../apis/planModul';
import { WeaLocaleProvider } from 'ecCom';
import {WeaForm} from 'comsMobx';
import moment from 'moment';
import {WeaLogView} from 'comsMobx'
import {Modal} from 'antd';
const {LogStore} = WeaLogView;
const getLabel = WeaLocaleProvider.getLabel;

import * as MultiOptions from '../../components/PlanModul/constants/MultiOptions';

import {FormFields} from '../../components/PlanModul/constants/FormFields';


export default class PlanModulStore extends CommonStore {
  //test = '周期日程';
  @observable
  hasRight=true;
  @observable logStore = new LogStore();
  @observable maxRepeatDate = 0;
  @observable oldSecretLevel='4';
  constructor() {

    super();
    this.pageName = 'planModul';

    // this.addWorkPlanFormAttrs

    //代表添加计划模板的那个表单中不由wea-form管理的所有字段的字段的默认值
    this.addWorkPlanFormOtherParamsDefaults = {
      "isremind": 0, //是否提醒默认值
      "remindBeforeStart": "0",
      "remindBeforeEnd": "0",

      "remindDateBeforeStart": "0",
      "remindTimeBeforeStart": "10",
      "remindDateBeforeEnd": "0",
      "remindTimeBeforeEnd": "10",

      "timeModul": MultiOptions.regularModeOptions()[0].key,
      "interval":1,
      "fer_0": MultiOptions.optionsOfSelectAWeekDay()[0].key, //每周周几默认值
      "monthType": MultiOptions.optionsOfSelectAOrder()[0].key, //每月正/倒数默认值
      "fer_1": MultiOptions.optionsOfSelectAMonthDay[0].key, //月天数下拉框默认值
      "fer_2": MultiOptions.optionsOfSelectAMonth[0].key, //年月数下拉框默认值
      "yearType": MultiOptions.optionsOfSelectAOrder()[0].key, //每年正/倒数默认值,
      "fery": MultiOptions.optionsOfSelectAMonthDay[0].key,  //年天数下拉框默认值
      "switchWeek":MultiOptions.optionsOfSwitchWeek()[0].key, //年月 日期/星期 下拉框
      "fer_3": MultiOptions.optionsOfWeekIndex()[0].key, //年月 星期模式下 第几周 默认值
      "timeType": '2', //日程持续类型默认值
    };

    //代表添加计划模板的那个表单中由wea-form管理的一些基础必要的默认值(不包括新建模板时才需要的)
    this.addWorkPlanFormDdfaults = {
      
    };
    

    //代表当前正在编辑的周期日程的id，-1表示是在新建计划模板，整数则代表正在编辑
    this.id = -1;

  }

  @observable addWorkPlanFormConditionInfo = {};

  //控制添加计划模板中几个相关xx字段的显隐的obj
  @observable ifHideSomeAboutFieldObj = {
    ifHideReletedWF: false,
    ifHideReletedcrm: false,
    ifHideReletedProject: false,
    ifHideReletedDoc: false,
    ifHideReletedTask: false,
    ifHideRemindType: false,
  };

  @action setOldSecretLevel = (val) => this.oldSecretLevel = val;

  //每次新建或编辑计划模板时重新获取表单中各相关xx字段的hide属性
  @action
  setIfHideSomeAboutFieldObj() {
    PLANMODULAPI.getBaseData().then(action(data => {
      let {doc, crm, prj, wf, task} = data.resource;
      let isRemindTypes = data&&data.remindTypes&&data.remindTypes.length===0 ? true : false;
      this.maxRepeatDate = data.maxRepeatDate;
      this.ifHideSomeAboutFieldObj = {
        ...this.ifHideSomeAboutFieldObj,
        ifHideReletedDoc: !doc,
        ifHideReletedcrm: !crm,
        ifHideReletedProject: !prj,
        ifHideReletedWF: !wf,
        ifHideReletedTask: !task,
        ifHideRemindType: isRemindTypes
      };
    }));
  }

  setState = (params={}, callback) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
    typeof callback === 'function' && callback();
  }

  //在第一次加载该组件时从后台获取初始化addworkmodelform中的wea-form部分需要的一些值
  //并初始化这个wea-form
  @action
  initAddWorkPlanFormFields = () => {
    
    this.addWorkPlanFormConditionInfo=FormFields().condition;

    //AddWorkPlanForm中由wea-form托管的所有字段的attrs集合
    this.allAddWorkPlanFormParamsAttrs = this.addWorkPlanFormConditionInfo[0].items
      .filter(elem => elem.conditionType !== "CUSTOME")
      .map(elem => {
        return toJS(elem).domkey[0];
      })
    
    this.addWorkPlanFormOtherParamsDefaults={...this.addWorkPlanFormOtherParamsDefaults,...{
      //默认值初始化
      "timeModul": MultiOptions.regularModeOptions()[0].key,
      "interval":1,
      "fer_0": MultiOptions.optionsOfSelectAWeekDay()[0].key, //每周周几默认值
      "monthType": MultiOptions.optionsOfSelectAOrder()[0].key, //每月正/倒数默认值
      "fer_1": MultiOptions.optionsOfSelectAMonthDay[0].key, //月天数下拉框默认值
      "fer_2": MultiOptions.optionsOfSelectAMonth[0].key, //年月数下拉框默认值
      "yearType": MultiOptions.optionsOfSelectAOrder()[0].key, //每年正/倒数默认值,
      "fery": MultiOptions.optionsOfSelectAMonthDay[0].key,  //年天数下拉框默认值
      "switchWeek":MultiOptions.optionsOfSwitchWeek()[0].key, //年月 日期/星期 下拉框
      "fer_3": MultiOptions.optionsOfWeekIndex()[0].key, //年月 星期模式下 第几周 默认值
      "timeType": '1', //日程持续类型默认值
      "beginDate":moment().format('YYYY-MM-DD')
    }}
    
    // this.addWorkPlanForm.initFormFields(toJS(this.addWorkPlanFormConditionInfo));
    PLANMODULAPI.getBaseData().then(action(data => {
      let items = toJS(this.addWorkPlanFormConditionInfo[0].items);
      let newType_n_Options = JSON.parse(JSON.stringify(MultiOptions.type_n_Options)),
        newRemindTypeOptions = JSON.parse(JSON.stringify(MultiOptions.remindTypeOptions())),
        newSecretLevelOption = JSON.parse(JSON.stringify(MultiOptions.secretLevelOption));;
      let {remindTypes, selectType, secretLevelOption,isOpenSecret,browserDataSqlWhere,completeDataSqlWhere} = data;

      //日程提醒方式options里动态添加options
      let remindTypeDefault = [];
      this.workPlanFormFieldsDatas = data;
      remindTypes.forEach((elem) => {
        if (elem.isdefault === "1") {
          remindTypeDefault.push(elem.id)
          newRemindTypeOptions.push({
            key: elem.id,
            showname: elem.label,
            selected: true,
          });
        } else {
          newRemindTypeOptions.push({
            key: elem.id,
            showname: elem.label,
            selected: false,
          });
        }
      });
      if(remindTypeDefault.length > 0){
        this.addWorkPlanFormDdfaults = {
          remindType: remindTypeDefault.join(','),
        };
      }

      //日程类型options里动态添加options
      newType_n_Options = selectType.map((elem) => {
        if (elem.key === "0") {//工作安排
          return {...elem, selected: true};
        } else {
          return {...elem, selected: false};
        }
      });

      if(isOpenSecret){
        newSecretLevelOption = secretLevelOption.map((elem) => {
          if (elem.key === "3") {//内部
            return {...elem, selected: true};
          } else {
            return {...elem, selected: false};
          }
        });
      }

      this.addWorkPlanFormConditionInfo[0].items.forEach((elem, index) => {
        if (toJS(elem.domkey[0]) === 'workPlanType') {//日程类型
          this.addWorkPlanFormConditionInfo[0].items[index].options = newType_n_Options;
        } else if (toJS(elem.domkey[0]) === 'remindType') {//日程提醒方式
          this.addWorkPlanFormConditionInfo[0].items[index].options = newRemindTypeOptions;
        } else if (toJS(elem.domkey[0]) === 'secretLevel' && isOpenSecret) {//密级等级
          this.addWorkPlanFormConditionInfo[0].items[index].options = newSecretLevelOption;
          this.oldSecretLevel=data&&data.secretLevelOption&&data.secretLevelOption.length>0?'4':'';
        } else if (toJS(elem.domkey[0]) === 'secretLevel' && !isOpenSecret) {//密级等级
          this.addWorkPlanFormConditionInfo[0].items.splice(2,1);
        } else if (toJS(elem.domkey[0]) === 'principal' ) {//负责人
          this.addWorkPlanFormConditionInfo[0].items[index].browserConditionParam.dataParams = {sqlwhere:browserDataSqlWhere};
          this.addWorkPlanFormConditionInfo[0].items[index].browserConditionParam.completeParams = {sqlwhere:completeDataSqlWhere};
        }
      });

      this.addWorkPlanForm.initFormFields(toJS(this.addWorkPlanFormConditionInfo));

      this.addWorkPlanFormDdfaults.workPlanType = newType_n_Options[0].key;
      this.addWorkPlanFormDdfaults.urgentlevel = MultiOptions.urgentlevelOptions()[0].key;
      if(isOpenSecret){
        this.addWorkPlanFormDdfaults.secretLevel = newSecretLevelOption.length>0?newSecretLevelOption[0].key:'';
      }
      this.maxRepeatDate = data.maxRepeatDate;
    }));
  };

  //仅在第一次初始化计划模板时会用到，后续用不到了,
  //初始化新建模板的表单控件以便于渲染
  // @action
  // initAddWorkPlanFormFields() {
  //     this.addWorkPlanForm.initFormFields(this.addWorkPlanFormConditionInfo);
  // };

  @observable userList = [];

  //代表添加计划模板的表单
  @observable addWorkPlanForm = new WeaForm();

  //代表添加计划模板的那个表单中不由wea-form管理的所有字段的当前的值
  @observable addWorkPlanFormOtherParams = observable.map(this.addWorkPlanFormOtherParamsDefaults);

  //存储在新建计划模板时会用到的一些依赖于后台的默认值，包括标题、提交人、负责人的默认值
  @observable addWorkPlanFormBaseParamsDefaults = observable.map({});

  @observable saveLoading = false;

  //获取添加计划模板的表单中由wea-form的store管理的所有字段当前的值
  @action
  getAddWorkPlanFormParams() {
    return this.addWorkPlanForm.getFormParams();
  };

  //修改addWorkPlanFormOtherParams中的某属性的值
  @action
  setAddWorkPlanFormOtherParams = (key, val) => {
    if(key=='timeModul'){//修改重复模式时，清空公用的 日期/星期、周数、周几  三个select框的值
      this.addWorkPlanFormOtherParams.set('fer_0', MultiOptions.optionsOfSelectAWeekDay()[0].key);
      this.addWorkPlanFormOtherParams.set('switchWeek', MultiOptions.optionsOfSwitchWeek()[0].key);
      this.addWorkPlanFormOtherParams.set('fer_3', MultiOptions.optionsOfWeekIndex()[0].key);
    }
    this.addWorkPlanFormOtherParams.set(key, val);
  };

  //清空整个AddWorkPlanForm，包括weaform托管的和自己托管的，并给整个AddWorkPlanForm设定
  //必要的默认值(除去新建时才需要的默认值)
  //新建时才需要的默认值的设置参照setAddWorkPlanFormBaseParamsDefaults
  @action
  resetWholeAddWorkPlanFormAndSetSomeDefualts() {
    this.addWorkPlanForm.reset();
    this.addWorkPlanForm.updateFields(this.addWorkPlanFormDdfaults);
    this.addWorkPlanFormOtherParams.replace(this.addWorkPlanFormOtherParamsDefaults);
  }

  //用于设置在新建时会用到的一些依赖于后台的默认值，包括标题、提交人、负责人的默认值
  @action setAddWorkPlanFormBaseParamsDefaults() {

    //表示之前已经从后台获取过数据了，所以不需要重新获取了
    if (toJS(this.addWorkPlanFormBaseParamsDefaults).name !== undefined &&
      toJS(this.addWorkPlanFormBaseParamsDefaults).name !== "") {

      this.addWorkPlanForm.updateFields(toJS(this.addWorkPlanFormBaseParamsDefaults));

    } else {

      //表示这是第一次从后台获取过数据
      PLANMODULAPI.getBaseData().then((data) => {
        this.addWorkPlanFormBaseParamsDefaults.replace({
          name: data.planName,
          submiter: data.submiter,
          principal: data.principal,
        });
        this.addWorkPlanForm.updateFields(toJS(this.addWorkPlanFormBaseParamsDefaults));
        this.oldSecretLevel=data&&data.secretLevelOption&&data.secretLevelOption.length>0?'4':'';
      })
    }

  }


  //在新建计划模板时，设置新建几乎模板需要的默认值
  //包括：1.重置整个表单，2.设置基础的默认值以及新建才需要的默认值
  @action
  doNewData() {
    this.id = -1;
    this.hasRight=true;
    this.resetWholeAddWorkPlanFormAndSetSomeDefualts();
    this.setAddWorkPlanFormBaseParamsDefaults();
  }

  //保存计划模板时做的事情：
  //1.把数据传给后台
  //2.保存成功后重新搜索表格以渲染最新添加或编辑的数据
  //3.清空整张计划模板表单的值并设置必要的默认值(除去新建时才需要的默认值)
  //3.关闭弹窗
  @action
  doSave() {
    //表示将要传给后台的数据

    //年月新增 月的周模式：第几个周几 
    //目前只支持单选   参数处理  fer_3=周数,周几
    let addWorkPlanParamTemp=toJS(this.addWorkPlanFormOtherParams);
    if(addWorkPlanParamTemp.switchWeek){
      if(addWorkPlanParamTemp.switchWeek=='1'){//周模式
        addWorkPlanParamTemp.fer_3=addWorkPlanParamTemp.fer_3+","+addWorkPlanParamTemp.fer_0;
      }
    }
    
    let WholdDataObj = {...toJS(this.getAddWorkPlanFormParams()), ...addWorkPlanParamTemp};
    //编辑而非新建计划模板时要向后台传id
    if (this.id !== -1) {
      WholdDataObj = {...WholdDataObj, id: this.id};
    }
    let canAdd = true;
    if(WholdDataObj.immediatetouch == '1'){
      canAdd = this.chkTime(WholdDataObj.endDate)
    }
    if(canAdd){
      this.saveLoading = true;
      PLANMODULAPI.add(WholdDataObj).then(action("saveSuccess", data => {
        this.saveLoading = false;
        this.oldSecretLevel=WholdDataObj.secretLevel;
        if (data.status) {
          this.doSearch();
          this.resetWholeAddWorkPlanFormAndSetSomeDefualts();
          this.closeAddDialog();
        }
        
      }));
    }else{
      this.AlertModal(getLabel(507215, '您提交的周期日程超出跨度限制，请联系管理员'))
    }
    
  }

  chkTime = (enddate)=>{
    if (this.maxRepeatDate != '' && enddate > this.maxRepeatDate) {
      return false;
    } else {
      return true;
    }
  }

  AlertModal = (alertText) => {
    return (
        Modal.warning({
            title : `${getLabel(15172,'系统提示')}`,
            content: alertText,
            onOk: () => {},

        })

    );
}

  //id表示表格当前行的id
  @action
  doEdit(id) {
    this.id = id;
    PLANMODULAPI.viewPlanModul({id: id}).then(action("fetchTableRowDataDetaisSuccess", data => {
      this.oldSecretLevel = data['secretLevel'];
      if(data.ret&&data.ret=='noright'){
        this.hasRight=false;
      }else{
        this.hasRight=true;
        this.resetWholeAddWorkPlanFormAndSetSomeDefualts();
        //得到AddWorkPlanFormParams对象中的所有attrs
        this.allAddWorkPlanFormParamsAttrs.forEach((elem, index) => {
          data && data[elem] && this.addWorkPlanForm.updateFields({
            [elem]: data[elem]
          });
          delete data[elem];
  
        });
        this.addWorkPlanFormOtherParams.merge(data);
      }
      this.openAddDialog();

    }));
  }


  @observable ifShowAlertModal = false;

  @action
  setIfShowAlertModal(newBool) {
    this.ifShowAlertModal = newBool;
  }

  //新建计划工作模板中定期模式中select的值
  @observable regularModeSelectVal = '';

  @action setRegularModeSelectVal(val) {
    this.regularModeSelectVal = val;
  }


  @action
  addUser(params) {
    this.userList.push({name: "dyf"});
  }

  getUserList(params) {
    return this.userList.slice();
  }
}
